package com.tt.vtg.scenario.http.decoder;

import com.tt.vtg.scenario.http.HttpJsonRequest;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;
import java.util.List;

public class HttpJsonRequestDecoder<CLZ> extends AbstractHttpJsonDecoder<FullHttpRequest, CLZ> {
    public HttpJsonRequestDecoder(Class<CLZ> clz){
        super(clz);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, FullHttpRequest req, List<Object> out) throws Exception {
//        System.out.println("HttpJsonRequestDecoder...");
        if (req.decoderResult().isFailure() || req.method() != HttpMethod.POST){
            sendError(ctx);
            return;
        }

        CLZ obj = _decode(req.content());
        if(obj == null) {
            sendError(ctx);
            return;
        }
        out.add(new HttpJsonRequest<>(obj, req));
    }

    private void sendError(ChannelHandlerContext ctx){
        String errMsg = "Request method should be POST, and format as below:\n" +
                "{\n" +
                "\t\"userId\" : \"***\",\n" +
                "\t\"action\" : \"ADD / SUB / INIT\",\n" +
                "\t\"amount\" : ***\n" +
                "}";

        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.BAD_REQUEST, Unpooled.copiedBuffer(errMsg, Charset.forName("utf-8")));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

        /*
           Send response then closing this channel / channelPipeline.
           If use:
                   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
           That can not close channel / channelPipeline.
        */

        // ctx.pipeline().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
